package cn.sciento.websocket.redis;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


import cn.sciento.core.convertor.ApplicationContextHelper;
import cn.sciento.core.redis.RedisHelper;
import org.apache.commons.lang3.ObjectUtils;
import cn.sciento.websocket.config.WebSocketConfig;
import org.springframework.context.ApplicationContext;

public class BrokerListenRedis {
    private static RedisHelper redisHelper;

    private static RedisHelper getRedisHelper() {
        ApplicationContext applicationContext = ApplicationContextHelper.getContext();
        if (redisHelper == null) {
            redisHelper = applicationContext.getBean(RedisHelper.class);
        }
        redisHelper.setCurrentDatabase(applicationContext.getBean(WebSocketConfig.class).getRedisDb());
        return redisHelper;
    }

    private static void clear() {
        if (redisHelper == null) {
            redisHelper = ApplicationContextHelper.getContext().getBean(RedisHelper.class);
        }
        redisHelper.clearCurrentDatabase();
    }

    private static String getCacheKey() {
        return "websocket:brokers";
    }

    public static void refreshCache(String brokerId) {
        getRedisHelper().hshPut(getCacheKey(), brokerId, "");
        clear();
    }

    public static List<String> getCache() {
        Set<String> set = ObjectUtils.defaultIfNull(getRedisHelper().hshKeys(getCacheKey()), new HashSet());
        clear();
        return new ArrayList<>(set);
    }

    public static void clearRedisCache(String brokerId) {
        getRedisHelper().hshDelete(getCacheKey(), brokerId);
        clear();
    }
}
